﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Common.Utilities.OpenXml
{
    /// <summary>
    /// 
    /// </summary>
    public class ExcelRangeHelper
    {
        /// <summary></summary>
        public static int GetColumnIndex(string name)
        {
            if (name.IndexOf(":") > 0)
                name = name.Substring(0, name.IndexOf(":"));
            Regex charRegex = new Regex("(^[^\\d]+)\\d+$");
            Match charMatch = charRegex.Match(name);
            Char[] colChars = null;
            if (charMatch.Success)
            {
                colChars = charMatch.Groups[1].Value.ToCharArray();
            }
            else
            {
                colChars = name.ToCharArray();
            }

            if (colChars.Length == 1)
            {
                return ExcelRangeHelper.Asc(colChars[0]) - ExcelRangeHelper.Asc('A') + 1;
            }
            else
            {
                int digit1 = (ExcelRangeHelper.Asc(colChars[0]) - ExcelRangeHelper.Asc('A') + 1) * 26;
                int digit2 = ExcelRangeHelper.Asc(colChars[1]) - ExcelRangeHelper.Asc('A') + 1;
                return digit1 + digit2;
            }
        }
        /// <summary></summary>
        public static string GetColumnName(int colIndex)
        {
            char left = ' ';
            char right = ' ';
            for (int i = 0; i < 26; i++)
            {
                for (int k = 0; k <= 26; k++)
                {
                    int index = i * 26 + k;
                    if (index == colIndex)
                    {
                        if (i > 0)
                        {
                            left = ExcelRangeHelper.Chr(64 + i);
                        }
                        right = ExcelRangeHelper.Chr(64 + k);

                        k = 100;
                        i = 100;
                        break;
                    }
                }
            }
            return string.Concat(left.ToString(), right.ToString()).Trim();
        }
        /// <summary></summary>
        public static int GetRowIndex(string name)
        {
            if (name.IndexOf(":") > 0)
                name = name.Substring(0, name.IndexOf(":"));
            Regex charRegex = new Regex("(^[^\\d]+)(\\d+)$");
            Match charMatch = charRegex.Match(name);
            int rowIndex = int.Parse(charMatch.Groups[2].Value);
            return rowIndex;
        }
        /// <summary></summary>
        public static int Asc(char c)
        {
            return (int)Encoding.ASCII.GetBytes(new char[] { c })[0];
        }
        /// <summary></summary>
        public static char Chr(int i)
        {
            return Convert.ToChar(i);
        }
    }
}
